﻿using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel.DomainServices.Client;
using ObservableCollections.Interfaces;

namespace ObservableCollections.Extensions
{
    public static class EntityExtender
    {
        public static void Undo(this Entity entity)
        {
            var rct = entity as IRevertibleChangeTracking;
            if (rct != null)
                rct.RejectChanges();
            var de = entity as IDuplicateAwareEntity;
            if (de != null)
                de.Reset();
        }

        public static void AcceptChanges(this Entity entity)
        {
            var ct = entity as IChangeTracking;
            ct.AcceptChanges();
        }

        public static string Serialize<T>(this T entity) where T:Entity
        {
            var serializer = new DataContractSerializer(typeof(T));
            using (var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, entity);
                ms.Position = 0;
                using (var sr = new StreamReader(ms))
                {
                    string result = sr.ReadToEnd();
                    return result;
                }
            }
        }
    }
}
